package cqrtplm.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

@Component
@Slf4j
public class FTPUtil {
    private static final FTPClient ftpClient = new FTPClient();

    // 连接到 FTP 服务器
    public static void connect(String server, int port, String user, String password) throws IOException {
        ftpClient.connect(server, port);
        ftpClient.login(user, password);
        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
        int reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            throw new IOException("FTP server refused connection.");
        }
    }

    // 上传文件到 FTP 服务器
    public static boolean uploadFile(String localFilePath, InputStream inputStream) throws IOException {
            return ftpClient.storeFile(localFilePath, inputStream);
    }

    // 从 FTP 服务器下载文件
    public static boolean downloadFile(String remoteFilePath, String localFilePath) throws IOException {
        try (OutputStream outputStream = Files.newOutputStream(Paths.get(localFilePath))) {
            return ftpClient.retrieveFile(remoteFilePath, outputStream);
        }
    }

    // 关闭 FTP 连接
    public static void disconnect() throws IOException {
        if (ftpClient.isConnected()) {
            ftpClient.logout();
            ftpClient.disconnect();
        }
    }
}
